//
//  ZYAuthViewController.swift
//  SwiftDemo1
//
//  Created by wangzhipan on 2025/6/9.
//

import Foundation
import UIKit
import WebKit
import SVProgressHUD

class ZYAuthViewController: UIViewController {
    
    private var webView = WKWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNavigationBar()
        setupWebView()
    }
}

// MARK: -UI相关
extension ZYAuthViewController {
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(clickCloseItem))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(clickFillItem))
        navigationItem.title = "登录页面"
    }
    
    private func setupWebView() {
        view.addSubview(webView)
        webView.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(0)
            make.top.equalTo(topBarHeight())
        }
        
        webView.backgroundColor = .white
        webView.navigationDelegate = self
        loadWebView()
    }
    
    private func loadWebView() {
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        
        guard let url = URL(string: urlStr) else {
            return
        }
        
        let request = URLRequest(url: url)
        webView.load(request)
    }
    
}

extension ZYAuthViewController {
    @objc private func clickCloseItem() {
        dismiss(animated: true) {
            SVProgressHUD.dismiss()
        }
    }
    
    @objc private func clickFillItem() {
//        let jsCode = "document.getElementById('userId').value='';document.getElementById('passwd').value='wzp19930827wzp';"
//        webView.evaluateJavaScript(jsCode) { (result, error) in
//            if let error = error {
//                print("JavaScript 执行错误: \(error)")
//            } else {
//                print("JavaScript 执行成功")
//                if let result = result {
//                    print("返回结果: \(result)")
//                }
//            }
//        }
        
        var jsCode = """
            var input = document.querySelector('input[aria-label="手机号或邮箱"]');
            if (input) {
                input.value = '1204473090@qq.com';
                input.dispatchEvent(new Event('input', { bubbles: true }));
                input.dispatchEvent(new Event('change', { bubbles: true }));
            }
        """

        webView.evaluateJavaScript(jsCode) { (result, error) in
            if let error = error {
                print("JavaScript 账号执行错误: \(error)")
            } else {
                print("账号注入成功")
            }
        }
        
        jsCode = """
            var passwordInput = document.querySelector('input[type="password"][aria-label="密码"]');
            if (passwordInput) {
                passwordInput.value = 'your_password_here';
                passwordInput.dispatchEvent(new Event('input', { bubbles: true }));
                passwordInput.dispatchEvent(new Event('change', { bubbles: true }));
                console.log('password filled successfully');
            } else {
                console.log('password input not found');
            }
        """

        webView.evaluateJavaScript(jsCode) { (result, error) in
            if let error = error {
                print("密码注入错误: \(error)")
            } else {
                print("密码注入完成")
            }
        }
    }
}

extension ZYAuthViewController: WKNavigationDelegate {
    //开始加载
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        SVProgressHUD.show()
    }
    
    //加载成功
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        SVProgressHUD.dismiss()
    }
    
    //加载失败
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: any Error) {
        SVProgressHUD.dismiss()
        Logger.info(error.localizedDescription)
    }
    
    //初始加载失败
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: any Error) {
        SVProgressHUD.dismiss()
        Logger.info(error.localizedDescription)
    }
    
    // 决定导航策略
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) {
        
        guard let url = webView.url else {
            decisionHandler(.allow)
            return
        }
        
        let urlStr = url.absoluteString
        
        if !urlStr.contains("code=") {
            decisionHandler(.allow)
            return
        }
        
        if let code = urlStr.components(separatedBy: "code=").last {
            requestAccessToken(code: code)
        }
        decisionHandler(.cancel)
    }
}

// MARK: -请求
extension ZYAuthViewController {
    private func requestAccessToken(code: String) {
        ZYRequestCore.shareCore.loadAccessToken(code: code) { result in
            switch result {
            case .failure(let error):
                Logger.info(error.localDesc)
            case .success(let account):
                self.handleAccessTokenRequest(account)
            }
        }
    }
    
    private func handleAccessTokenRequest(_ account: ZYUserAccount) {
        ZYRequestCore.shareCore.loadUserInfo(account: account) { result in
            switch result {
            case .failure(let error):
                Logger.info(error.localDesc)
            case .success(let tempInfo):
                self.handleUserInfoRequest(account, tempInfo)
            }
        }
    }
    
    private func handleUserInfoRequest(_ account: ZYUserAccount, _ tempInfo: ZYUserTempInfo) {
        account.avatar_large = tempInfo.avatar_large
        account.screen_name = tempInfo.screen_name
        ZYUserCore.shareCore.account = account
        NotificationCenter.default.post(name: .init(VcReloadViewNote), object: nil)
        self.dismiss(animated: true)
    }
}
